import React, { useState,useCallback } from 'react';
import { 
  Modal, Form, Input, Select, DatePicker, Radio, Table, Button, Space, 
  message
} from 'antd';
import { Subscribe } from '../setmeal/findex';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import type { GetProps } from 'antd';
type SearchProps = GetProps<typeof Input.Search>;
import type { IMembers } from '../types/members';
import http from '~/api/http';
const { Search } = Input;

// 预约表单值类型
interface OrderFormValues {
  orderName: string;        // 预约人姓名
  fileNumber: string;      
  // 档案号
  idCard: string;           // 身份证号
  birthDate: dayjs.Dayjs | null; // 出生日期（改为Dayjs类型适配DatePicker）
  phone: string;            // 预约电话
  gender: 'male' | 'female';// 性别
  age: number;              // 年龄
  orderDate: dayjs.Dayjs | null; // 预约日期（改为Dayjs类型适配DatePicker）
  selectedPackages: string[]; // 选中的套餐ID数组
}

interface props {
  visible: boolean
  ff:()=>void
}

const Sub: React.FC<props> = ({ visible,ff }) => {


  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm<OrderFormValues>();       // 表单实例
const [zhi,setzhi]=useState({})


  // 打开弹窗（重置表单）

  const showModal = () => {
    setIsModalOpen(true);
    form.resetFields();
  };

  // 关闭弹窗（重置表单）
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
    ff()
  };

  // 表单提交逻辑
  const handleFinish = (values: OrderFormValues) => {
    
    if (uu === 0) {
      message.error("请选择套餐");
      return;
    }
    
    // 转换日期格式为字符串以便提交
  
    
   

    // 转换日期格式为 年月日（YYYY-MM-DD）字符串
  const submitData = {
    ...values,
    // 处理出生日期（如果有值则转换，否则为null）
    birthDate: values.birthDate?.format('YYYY-MM-DD') || null,
    // 处理预约日期（核心：转换为年月日字符串）
    orderDate: values.orderDate?.format('YYYY-MM-DD') || null,
    // 其他字段保持不变
  };
  
  console.log('提交的预约日期（年月日）：', submitData.orderDate); // 输出格式如 "2025-10-23"
    
 http.post("Order",{id: 0,
  memberId:zhi.id,
  orderDate:submitData.orderDate,
  orderType: "电话预约",
  ids:kk}).then(res=>{
    if(res.code=="1"){
    message.success(res.msg)
    handleCancel()
    }
  })


    
  };

  const [uu, setuu] = useState(0);
  const [kk, setkk] = useState([]);

   

 
  const pp = (value: number) => {
    setuu(value);
  };
  
  const oo = (value: []) => {
    setkk(value);
  };

  // 档案号搜索处理
  const onSearch: SearchProps['onSearch'] = (value) => {
    if (!value) {
      message.warning('请输入档案号');
      return;
    }
    
    http.get<IMembers>("Member/fileNumber", { id: value }).then(res => {
    
      setzhi(res.data)
      // 假设接口返回的数据结构与IMembers一致
      // 这里根据实际接口返回的字段名进行调整
      const memberInfo = res.data;
      
      if (memberInfo) {
        // 将查询结果填充到表单
        form.setFieldsValue({
          fileNumber: memberInfo.fileNumber,
          orderName: memberInfo.name,        // 假设姓名字段为name
          idCard: memberInfo.idCard,
          // 转换为dayjs对象适配DatePicker
          birthDate: memberInfo.birthday ? dayjs(memberInfo.birthday) : null,
          phone: memberInfo.phoneNumber,
          // 假设性别字段返回的是'male'或'female'，如果不是需要转换
          gender: memberInfo.sex === '男' ? 'male' : 'female',
          age: memberInfo.age
        });
        message.success('档案信息加载成功');
      } else {
        message.warning('未找到对应档案信息');
      }
    }).catch(err => {
      console.error('查询失败：', err);
      message.error('查询失败，请稍后重试');
    });
  };

  return (
    <>
      <Button variant="solid" color="pink" onClick={showModal}>
        预约新增
      </Button>

      <Modal
        title="添加预约信息"
        open={isModalOpen}
        onCancel={handleCancel}
        footer={[
          <Space 
            key="footer-buttons" 
            style={{ 
              width: '100%',
              justifyContent: 'center'
            }}
          >
            <Button key="cancel" onClick={handleCancel}>取消</Button>
            <Button key="submit" type="primary" onClick={() => form.submit()}>确认提交</Button>
          </Space>
        ]}
        width={1500}
        centered 
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleFinish}
        >
          <Space direction="vertical" size={16}>
            <div style={{ display: 'flex', gap: 24 }}>
              <div style={{ flex: 2 }}>
                <Form.Item
                  name="fileNumber"
                  label="档案号"
                  rules={[{ required: true, message: '请输入档案号' }]}
                >
                  <Search  placeholder="输入档案号搜索" onSearch={onSearch} style={{ width: 200 }} />
                </Form.Item>
                
                <Form.Item
                 
                  name="orderName"
                  label="预约人姓名"
                  rules={[{ required: true, message: '请输入预约人姓名' }]}
                >
                  <Input readOnly placeholder="请输入预约人姓名" />
                </Form.Item>

                <Form.Item
                  name="idCard"
                  label="身份证"
                  rules={[{ required: true, message: '请输入身份证号' }]}
                >
                  <Input readOnly placeholder="请输入身份证号" />
                </Form.Item>

                <Form.Item
                  name="birthDate"
                  label="出生日期"
                  rules={[{ required: true, message: '请选择出生日期' }]}
                >
                  <DatePicker disabled={true} placeholder="请选择出生日期" />
                </Form.Item>

                <Form.Item
                  name="phone"
                  label="预约人电话"
                  rules={[{ required: true, message: '请输入预约人电话' }]}
                >
                  <Input readOnly placeholder="请输入预约人电话" />
                </Form.Item>

                <Form.Item
                  name="gender"
                  label="预约人性别"
                  rules={[{ required: true, message: '请选择性别' }]}
                >
                  <Radio.Group disabled={true} >
                    <Radio value="male" >男</Radio>
                    <Radio value="female">女</Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  name="age"
                  label="预约人年龄"
                  rules={[{ required: true, message: '请输入年龄' }]}
                >
                  <Input readOnly type="number" placeholder="请输入年龄" />
                </Form.Item>

                <Form.Item
                  name="orderDate"
                  label="预约日期"
                  rules={[{ required: true, message: '请选择预约日期' }]}
                >
                  <DatePicker
                    placeholder="请选择预约日期"
                    format="YYYY-MM-DD"
                    style={{ width: '100%' }}
                    disabledDate={(current) => current && current < dayjs().startOf('day')}
                  />
                </Form.Item>
              </div>

              <div style={{ flex:12 }}>
                <Form.Item label="套餐信息">
                  <Subscribe uu={pp} bb={oo}></Subscribe>
                </Form.Item>
              </div>
            </div>
          </Space>
        </Form>
      </Modal>
    </>
  );
};

export { Sub };